import './modeler.css';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';

import { defineComponent, onMounted } from 'vue';
import customModule from "./custom"; // 自定义内容
import createDefaultBpmnXml from '../../bpmn/defaultBpmnXml';
import activitiModdel from '../../bpmn/resources/activiti-moddel.json';
import translate from '../../bpmn/i18n';
import { BpmnStore } from '../../bpmn/store';

export default defineComponent({
  name: 'Modeler',
  props: {
    xml: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const bpmnContext = BpmnStore;
    onMounted(() => {
      bpmnContext.initModeler({
        container: '#modeler-container',
        additionalModules: [
          customModule, // 用自定义调色板、元素样式
          { translate: ['value', translate('zh')] },//添加翻译
        ],
        moddleExtensions: {
          activiti: activitiModdel,
        },
      });
      const defaultProcessIdAndName = '1';
      bpmnContext
        .importXML(props.xml || createDefaultBpmnXml(defaultProcessIdAndName, defaultProcessIdAndName))
        .then((result: Array<string>) => {
          if (result.length) {
            console.warn('importSuccess warnings', result);
          }
        })
        .catch((err: any) => {
          console.warn('importFail errors ', err);
        });

      /**
       * 事件注册
       * 当流程数据发生改变 向父组件抛出新xml数据
       */
      bpmnContext.addEventListener('element.changed', async () => {
        const { xml } = await bpmnContext.getXML();
        emit('update:xml', xml)
      })
    });

    // 拖拽事件
    const handleFileSelect = (e: any) => {
      e.stopPropagation();
      e.preventDefault();

      const files: any = e.dataTransfer.files;
      const file: any = files[0];
      const reader: FileReader = new FileReader();

      reader.onload = function (e) {
        const xml: string | ArrayBuffer = e.target.result;
        bpmnContext.importXML(xml.toString());
      };
      reader.readAsText(file);
    }

    const handleDragOver = (e: any) => {
      e.stopPropagation();
      e.preventDefault();

      e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }


    return () => (
      <div
        id="modeler-container"
        onDrop={e => handleFileSelect(e)}
        onDragover={e => handleDragOver(e)}
      />
    );
  },
});
